import { ref, reactive, onMounted, nextTick, watch, defineProps } from 'vue'
import { getAuthority } from "../../utils/permission";
import {ElMessage, ElMessageBox} from "element-plus";

export function usePageList (opts) {

  let option = reactive({
    showOverflowTooltip: true,
    hRBtns: [
      { title: '新增', id: 'newData', type: 'primary', event: newData }
    ],
    //表格
    cols: opts.cols || [],
    colBtns: [
      { title: '编辑', id: 'edit', type: 'primary', event: rowEdit },
      { title: '删除', id: 'delete', type: 'danger', event: rowDel },
    ],
    //分页
    showPage: true,
  }),

    query = reactive({}),
    defDialogData = reactive({}),

    tableLoading = ref(false),
    tableData = ref([]),

    page = reactive({
      total: 0,
      currentPage: 1,
      pageSize: 20
    }),

    dialogOption = reactive({
      title: '新增',
      fieldList: []
    }),
    dialogData = ref({}),
    dialogShow = ref(false),
    dialogRef = ref(null),
    // 权限
    isAppend = ref(true),
    isEdit = ref(true),
    isDelete = ref(true)



  /*监听分页*/
  watch(() => [page.pageSize, page.currentPage], function ([a, b], [c, d]) {
    getDataList();
  });

  prepare();

  function getDataList () {

    tableLoading.value = true;
    let param = {
      ...query,
      'page.no': page.currentPage,
      'page.size': page.pageSize
    };
    opts.getApi(param).then(res => {
      tableLoading.value = false;
      // opts.callbackList.getApi = null
      if (res.errcode != 0) return;
      tableData.value = res.row;
      console.log(tableData.value, 1111111111111111);
      // opts.callbackList.getApi = res.row
      page.total = res.total;
    })
  }

  function newData () {
    if (!isAppend.value) {
      ElMessage({
        type: 'warning',
        message: '抱歉，您没有权限新增该模块数据'
      })
      return
    }
    dialogOption.title = '新增';
    dialogData.value = defDialogData;
    dialogShow.value = true;
    dialogOption.fieldList.map(item => {
      if (item.editDisabled) item.disabled = false;
    })
  }
  async function rowEdit (scope, id) {
    if (!isEdit.value) {
      ElMessage({
        type: 'warning',
        message: '抱歉，您没有权限编辑该模块数据'
      })
      return
    }
    dialogOption.title = '编辑';
    let obj = {};
    dialogOption.fieldList.forEach(item => {
      if (item.editDisabled) item.disabled = true;
      let val = scope.row[item.show_field || item.field_id]
      val && (obj[item.field_id] = val)
    });
    obj.row_id = scope.row.row_id;

    dialogData.value = obj;
    dialogShow.value = true;
  }
  function rowDel (scope, id) {
    if (!isDelete.value) {
      ElMessage({
        type: 'warning',
        message: '抱歉，您没有权限删除该模块数据'
      })
      return
    }
    ElMessageBox.confirm('确定删除该数据？', '删除', {
      'cancelButtonText': '取消',
      'confirmButtonText': '确定',
      callback: (action) => {
        if (action === 'confirm') {
          let param = {};
          opts.idKey.forEach(item => param[item] = scope.row[item])
          opts.delApi(param).then(res => {
            if (res.errcode !== 0) return;
            ElMessage({
              type: 'success',
              message: `删除成功`,
            });
            getDataList();
            opts.deleteCallback && opts.deleteCallback();
          })
        }
      },
    })

  }

  function dialogConfirm (obj) {
    let { data, option } = obj,
      isAdd = option.title.indexOf('新增') >= 0;
    let pm = new Promise(resolve => {
      if (isAdd) {
        opts.addApi(data).then(res => {
          if (res.errcode !== 0) return;
          resolve(data);
        })
      } else {

        opts.editApi(data).then(res => {
          if (res.errcode !== 0) return;
          resolve(data);
        })
      }
    });

    pm.then(() => {
      ElMessage({
        message: option.title + '成功',
        type: 'success',
      })
      dialogRef.value.close();
      getDataList();
      opts.confirmCallback && opts.confirmCallback();
    })
  }


  function prepare () {
    let auth = getAuthority(opts.auth_id);
    if (auth) {
      isAppend.value = auth.is_append
      isDelete.value = auth.is_delete
      isEdit.value = auth.is_edit
      !auth.is_append && option.hRBtns.pop();
      !auth.is_edit && option.colBtns.shift();
      !auth.is_delete && option.colBtns.pop();
    }
  }

  return {
    option, tableLoading, tableData, query, page, dialogShow, dialogData, defDialogData, dialogOption, dialogRef,
    isAppend, isEdit, isDelete,
    getDataList, dialogConfirm

  }
}
